import winston from "winston"
import fs from "fs"

const fsPromises = fs.promises

async function getLogger() {
    const now = new Date()
    const logsDir = './logs'
    const infoLogFileName = `${logsDir}/${now.toDateString()}_info.log`
    const errLogFileName = `${logsDir}/${now.toDateString()}_error.log`

    await fsPromises.mkdir(logsDir, { recursive: true })
    await createLogFile(infoLogFileName)
    await createLogFile(errLogFileName)

    const { combine, label, timestamp, printf } = winston.format
    const standardFormat = printf(({ level, message, label, timestamp }) => {
        return `${timestamp} [${label}] ${level}: ${message}`
    })
    const logger = winston.createLogger({
        format: combine(label({ label: "frp" }), timestamp(), standardFormat),
        transports: [
            new winston.transports.File({ filename: errLogFileName, level: "error" }),
            new winston.transports.File({ filename: infoLogFileName }),
        ],
    })
    return logger
}

async function createLogFile(fileName) {
    try {
        await fsPromises.access(fileName, fsPromises.constants.F_OK)
    } catch {
        await fsPromises.appendFile(fileName, "")
    }
}

const logger = await getLogger()

export default logger
